#!/bin/sh
########
filename="/root/.bin/pac5.sh"
day_num=1

xf_cmd='/usr/bin/aria2c'
#mirr_1st='ftp://ftp.archlinux.org/'
mirr_1st='http://mirrors.kernel.org/archlinux/'
mirr_2nd='ftp://mirrors.ustc.edu.cn/archlinux/'
mirrorlist_file=/etc/pacman.d/mirrorlist
sed3(){
  sed -i "s:^$2XferCommand = $xf_cmd :$3XferCommand = $xf_cmd :g" /etc/pacman.conf
  echo  'Server = '$1'$repo/os/$arch'>$mirrorlist_file
  cat /etc/pacman.d/mirrorlist |grep "^Server"
}
do_pac(){
cat /etc/pacman.conf |grep "^XferCommand = $xf_cmd"
if [ $? -ne 0 ] ; then
  sed3  $mirr_2nd '#' ''
  yes|/usr/bin/pacman -Suw
else
  sed3  $mirr_1st '' '#'
  /usr/bin/pacman -Sy || return 1
fi
}
get_num1(){
  pa_sy=/var/lib/pacman/sync/ 
  filename1=$pa_sy`ls -t $pa_sy|head -1`
  ((num1=(`date +%s` - `date -r $filename1 +%s`) / 3600 ))
  (( day_h= day_num * 24 - 1))
  echo  $num1
  echo -------------`date`------------------
}
root_do(){
  tmp_file=`mktemp`
  sed -i "s:^#XferCommand = $xf_cmd :XferCommand = $xf_cmd :g" /etc/pacman.conf
  cp -p $mirrorlist_file $tmp_file
  do_pac 
  do_pac 
  mv $tmp_file $mirrorlist_file
}
main(){
  get_num1
  if [[ "$num1" -ge "$day_h" || $num1 -eq 0 ]]; then
    if [ `whoami` == 'root' ];then
      root_do
    else
      echo "not root"
    fi
  else
    echo "Don't worry, you'll be fine after $day_num days' rest."
  fi
}
main
